var pomelo = require('pomelo');
var utils = require('../../util/utils');
var Room = require('../../domain/common/room');
var roomDao = module.exports;

roomDao.createRoom = function (master, rid, userList, cb) {
    var sql = 'replace into room(master, rid, userlist) values(?, ?, ?)';
    var args = [master, rid, userList.join(',')];
    pomelo.app.get('dbclient').insert(sql, args, function (err, res) {
        if (!!err) {
            console.error('create room failed! ' + err.stack);
            utils.invokeCallback(cb, {code: err.number, msg: err.message}, null);
        } else {
            console.log('end create room');
            var room = new Room({id: res.id, rid: rid, master: master, userList: userList});
            utils.invokeCallback(cb, null, room);
        }
    });
};

roomDao.getRoom = function(rid, cb) {
    var sql = 'select * from room where rid = ?';
    var args = [rid];
    pomelo.app.get('dbclient').query(sql, args, function (err, res) {
        if (err) {
            utils.invokeCallback(cb, {code: err.number, msg: err.message}, null);
        } else {

            if (res.length > 0) {
                var row = res[0];
                var room = new Room({id: row.id, rid: row.rid, master: row.master, userList: row.userlist.split(',')});
                utils.invokeCallback(cb, null, room);
            } else {
                utils.invokeCallback(cb, null, {});
            }
        }
    });
};